<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\note\controller;

use app\base\BaseController;
use app\note\model\Note as NoteList;
use app\note\model\Diagnosis as DiagnosisList;
use app\user\model\Admin as AdminList;
use app\user\validate\AdminCheck;
use app\project\model\ProjectDocument as DocumentList;
use app\note\model\Recover;
use app\note\validate\NoteCheck;
use app\note\validate\DiagnosisCheck;
use app\note\validate\NoteCateCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;
use avatars\MDAvatars;
use Overtrue\Pinyin\Pinyin;

class expert extends BaseController
{
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            if (!empty($param['keywords'])) {
                $where[] = ['a.title|a.content', 'like', '%' . $param['keywords'] . '%'];
            }
            if(!empty($param['cate_id'])){
                $where[] = ['a.cate_id','=',$param['cate_id']];
            }
            //pr($where);
            $where[] = ['a.status', '>=', 0];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $note = DiagnosisList::where($where)
                ->field('a.*,c.title as cate_title')
                ->alias('a')
                ->join('NoteCate c', 'a.cate_id = c.id', 'LEFT')
                ->order('a.end_time desc,a.sort desc,a.create_time desc')
                ->paginate($rows, false, ['query' => $param])
                
                ->each(function ($item, $key) {
                    $item->start_time = empty($item->start_time) ? '-' : date('Y-m-d', $item->start_time);
                    $item->end_time = empty($item->end_time) ? '-' : date('Y-m-d', $item->end_time);
                });
            return table_assign(0, '', $note);
        } else {
            return view();
        }
    }
    /**
     * 在线问诊
     */
    public function diagnosis()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            if (!empty($param['keywords'])) {
                $where[] = ['a.title', 'like', '%' . $param['keywords'] . '%'];
            }
            if(!empty($param['cate_id'])){
                $where[] = ['a.cate_id','=',$param['cate_id']];
            }
            if (!empty($param['industry_id'])) {
                $where[] = ['industry_id', 'in', $param['industry_id']];
            }
            $where[] = ['a.status', '>=', 0];
            if($this->uid!=1){
                //$where[] = ['id', '=', $this->uid];
                $expert = Db::name('admin')->where(['id' => $this->uid])->find();
                $where[] = ['industry_id', 'in', $expert['industry_id']];
            }
            //pr($where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $note = DiagnosisList::where($where)
                ->field('a.*,c.title as cate_title')
                ->alias('a')
                ->join('industry c', 'a.industry_id = c.id', 'LEFT')
                //->order('a.end_time desc,a.sort desc,a.create_time desc')
                ->order('a.create_time desc')
                ->paginate($rows, false, ['query' => $param])
                
                ->each(function ($item, $key) {
                    $item->start_time = empty($item->start_time) ? '-' : date('Y-m-d', $item->start_time);
                    $item->end_time = empty($item->end_time) ? '-' : date('Y-m-d', $item->end_time);

                    $item->recover = Db::name('Recover')->where(['diagnosis_id'=>$item->id])->count();
                    $item->admin = Db::name('Admin')->where(['id' => $item->admin_id])->value('name');
                    $item->expert_name = Db::name('Admin')->where(['id' => $item->expert_id])->value('name');
                });
                //pr($note);
            return table_assign(0, '', $note);
        } else {
            $industry = Db::name('Industry')->select();
            $Recover = Db::name('Recover')->select();
            View::assign('industry', $industry);
            return view();
        }
    }
    /**
     * 专家列表
     */
    public function expert(){

        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            if (!empty($param['keywords'])) {
                $where[] = ['id|username|name|nickname|mobile|desc', 'like', '%' . $param['keywords'] . '%'];
            }
            if (isset($param['status']) && $param['status']!='') {
                $where[] = ['status', '=', $param['status']];
            }
            else{
                $where[] = ['status', '<', 2];
            }
            if (!empty($param['type'])) {
                $where[] = ['type', '=', $param['type']];
            }
            if (!empty($param['did'])) {
                $department_array = get_department_son($param['did']);
                $where[] = ['did', 'in', $department_array];
            }
            if (!empty($param['industry_id'])) {
                $where[] = ['industry_id', '=', $param['industry_id']];
            }else{
                $where[] = ['industry_id', '>=', 0];
            }
            if($this->uid!=1){
                $where[] = ['id', '=', $this->uid];
            }
            $where[] = ['type', '=', 1];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $admin = AdminList::where($where)
                ->order('id asc')
                ->paginate($rows, false, ['query' => $param])
                ->each(function ($item, $key) {
                    $item->department = Db::name('Department')->where(['id' => $item->did])->value('title');
                    $item->industry = Db::name('Industry')->where(['id' => $item->industry_id])->value('title');
                    $item->position = Db::name('Position')->where(['id' => $item->position_id])->value('title');
                    $item->entry_time = empty($item->entry_time) ? '-' : date('Y-m-d', $item->entry_time);
                    $item->last_login_time = empty($item->last_login_time) ? '-' : date('Y-m-d H:i', $item->last_login_time);
                    $item->last_login_ip = empty($item->last_login_ip) ? '-' : $item->last_login_ip;
                    
                });
            return table_assign(0, '', $admin);
        } else {
            $industry = Db::name('Industry')->select();
            View::assign('industry', $industry);
            View::assign('uid', $this->uid);
            return view();
        }
    }
    /**
     * 回复列表
     */
    public function recover_add()
    {
        $param = get_params();

        if (request()->isAjax()) {
            $param['expert_id'] = $this->uid;
            $param['add_admin'] = $this->uid;
            $param['create_time'] = time();
            $expert = Db::name('admin')->where(['id' => $this->uid])->find();
            $param['industry_id'] = $expert['industry_id'];
            $sid = Recover::strict(false)->field(true)->insertGetId($param);
            if ($sid) {
                $data_diagnosis['status'] =2;
                $diagnosis= Db::name('Diagnosis')->where(['id' => $param['diagnosis_id']])->update($data_diagnosis);
                add_log('add', $sid, $param);
                $users= Db::name('Admin')->field('id as from_uid')->where(['status' => 1])->column('id');
                $msg=[
                    'from_uid'=>$this->uid,
                    'title' => $param['content'],
                    'action_id'=>$sid
                ];
                sendMessage($users,1,$msg);
            }

            return to_assign(); 
            
        } else {
            $diagnosis_id = isset($param['diagnosis_id']) ? $param['diagnosis_id'] : 0;
            $recover = Db::name('Recover')->where(['diagnosis_id'=>$param['diagnosis_id']])->order('create_time desc')->select()->toArray();
            foreach($recover as $key =>$val){
                $expert=  Db::name('admin')->where(['id' => $val['expert_id']])->find();
                $recover[$key]['expert']=$expert['name'];
            }
            View::assign('diagnosis_id', $diagnosis_id);
            View::assign('recover', $recover);
            return view();
        } 
    }
    /**
     * 回复列表
     */
    public function recover_list()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            if (!empty($param['keywords'])) {
                $where[] = ['a.title', 'like', '%' . $param['keywords'] . '%'];
            }
            if(!empty($param['cate_id'])){
                $where[] = ['a.cate_id','=',$param['cate_id']];
            }
            if (!empty($param['industry_id'])) {
                $where[] = ['industry_id', 'in', $param['industry_id']];
            }
            $where[] = ['a.status', '>=', 0];
            if($this->uid!=1){
                //$where[] = ['id', '=', $this->uid];
                $expert = Db::name('admin')->where(['id' => $this->uid])->find();
                $where[] = ['industry_id', 'in', $expert['industry_id']];
            }
            //pr($where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $note = DiagnosisList::where($where)
                ->field('a.*,c.title as cate_title')
                ->alias('a')
                ->join('industry c', 'a.industry_id = c.id', 'LEFT')
                ->order('a.end_time desc,a.sort desc,a.create_time desc')
                ->paginate($rows, false, ['query' => $param])
                
                ->each(function ($item, $key) {
                    $item->start_time = empty($item->start_time) ? '-' : date('Y-m-d', $item->start_time);
                    $item->end_time = empty($item->end_time) ? '-' : date('Y-m-d', $item->end_time);
                });
                //pr($note);
            return table_assign(0, '', $note);
        } else {
            $industry = Db::name('Industry')->select();
            View::assign('industry', $industry);
            return view();
        }
    }
    /**
     * 供需平台
     */
    public function supply()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            if (!empty($param['keywords'])) {
                $where[] = ['a.title|a.content', 'like', '%' . $param['keywords'] . '%'];
            }
            if(!empty($param['cate_id'])){
                $where[] = ['a.cate_id','=',$param['cate_id']];
            }
            //pr($where);
            $where[] = ['a.status', '>=', 0];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $note = NoteList::where($where)
                ->field('a.*,c.title as cate_title')
                ->alias('a')
                ->join('NoteCate c', 'a.cate_id = c.id', 'LEFT')
                //->order('a.end_time desc,a.sort desc,a.create_time desc')
                ->order('id asc')
                ->paginate($rows, false, ['query' => $param])
                
                ->each(function ($item, $key) {
                    $item->start_time = empty($item->start_time) ? '-' : date('Y-m-d', $item->start_time);
                    $item->end_time = empty($item->end_time) ? '-' : date('Y-m-d', $item->end_time);
                });
            return table_assign(0, '', $note);
        } else {

            return view();
        }
    }
    //添加
    public function add()
    {
        $param = get_params();

        if (request()->isAjax()) {
            $param['start_time'] = isset($param['start_time']) ? strtotime(urldecode($param['start_time'])) : 0;
            $param['end_time'] = isset($param['end_time']) ? strtotime(urldecode($param['end_time'])) : 0;

            if (!empty($param['id']) && $param['id'] > 0) {
                try {
                    validate(diagnosisCheck::class)->scene('edit')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $param['update_time'] = time();
                $res = DiagnosisList::where('id', $param['id'])->strict(false)->field(true)->update($param);
                if ($res) {
                    add_log('edit', $param['id'], $param);
                }

                return to_assign();
            } else {
                $param['add_admin'] = $this->uid;
                try {
                    validate(NoteCheck::class)->scene('add')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $param['admin_id'] = $this->uid;
                $param['create_time'] = time();
                $sid = DiagnosisList::strict(false)->field(true)->insertGetId($param);
                if ($sid) {
                    add_log('add', $sid, $param);
					$users= Db::name('Admin')->field('id as from_uid')->where(['status' => 1])->column('id');
                    $msg=[
                        'from_uid'=>$this->uid,
                        'title' => $param['title'],
                        'action_id'=>$sid
                    ];
					sendMessage($users,1,$msg);
                }

                return to_assign();
            }
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $note = Db::name('Diagnosis')->where(['id' => $id])->find();
                //View::assign('note', $note);
                //$detail = (new DocumentList())->detail($param['id']);
                //$detail = (new DocumentList())->detail($param['id']);
                //pr($detail);
                //if($note['file_ids'] !=''){

                if(!empty($note['file_ids'])){
                    $fileArray = Db::name('File')->where('id','in',$note['file_ids'])->select();
                    $note['fileArray'] = $fileArray;
                }else{
                    $note['fileArray'] = '';
                }
                View::assign('note', $note);
            }
            $industry = Db::name('Industry')->select();
            View::assign('industry', $industry);
            View::assign('id', $id);
            return view();
        }
    }

    //查看
    public function view()
    {
        $id = empty(get_params('id')) ? 0 : get_params('id');
        $note = Db::name('Diagnosis')->where(['id' => $id])->find();
        $note['cate_title'] = Db::name('NoteCate')->where(['id' => $note['cate_id']])->value('title');
        $note['admin_name'] = Db::name('Admin')->where(['id' => $note['admin_id']])->value('name');
        View::assign('note', $note);
        return view();
    }

    //删除
    public function delete()
    {
        $id = get_params("id");
        $data['status'] = '-1';
        $data['id'] = $id;
        $data['update_time'] = time();
        if (Db::name('Diagnosis')->update($data) !== false) {
            add_log('delete', $id);
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "删除失败");
        }
    }
	
	//公告类别
    public function note_cate()
    {
        if (request()->isAjax()) {
            $cate = Db::name('NoteCate')->order('create_time asc')->select();
			$list = generateTree($cate);
            return to_assign(0, '', $list);
        } else {
            return view();
        }
    }

    //公告类别添加
    public function note_cate_add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            if (!empty($param['id']) && $param['id'] > 0) {
                try {
                    validate(NoteCateCheck::class)->scene('edit')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $note_array = admin_note_cate_son($param['id']);
                if (in_array($param['pid'], $note_array)) {
                    return to_assign(1, '父级分类不能是该分类本身或其子分类');
                } else {
                    $param['update_time'] = time();
                    $res = Db::name('NoteCate')->strict(false)->field(true)->update($param);
                    if ($res) {
                        add_log('edit', $param['id'], $param);
                    }
                    return to_assign();
                }
            } else {
                try {
                    validate(NoteCateCheck::class)->scene('add')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $param['create_time'] = time();
                $insertId = Db::name('NoteCate')->strict(false)->field(true)->insertGetId($param);
                if ($insertId) {
                    add_log('add', $insertId, $param);
                }
                return to_assign();
            }
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            $pid = isset($param['pid']) ? $param['pid'] : 0;
			$cate = $cate = Db::name('NoteCate')->order('id desc')->select()->toArray();
			$cates = set_recursion($cate);
            if ($id > 0) {
                $detail = Db::name('NoteCate')->where(['id' => $id])->find();
                View::assign('detail', $detail);
            }
            View::assign('id', $id);
            View::assign('pid', $pid);
            View::assign('cates', $cates);
            return view();
        }
    }

    //公告类别删除
    public function note_cate_delete()
    {
        $id = get_params("id");
        $cate_count = Db::name('NoteCate')->where(["pid" => $id])->count();
        if ($cate_count > 0) {
            return to_assign(1, "该分类下还有子分类，无法删除");
        }
        $content_count = Db::name('Note')->where(["cate_id" => $id,'status'=>1])->count();
        if ($content_count > 0) {
            return to_assign(1, "该分类下还有公告，无法删除");
        }
        if (Db::name('NoteCate')->delete($id) !== false) {
            add_log('delete', $id);
            return to_assign(0, "删除分类成功");
        } else {
            return to_assign(1, "删除失败");
        }
    }
    //添加
    public function expert_add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            //$param['entry_time'] = strtotime($param['entry_time']);
            $param['nickname'] = $param['name'];
            $pinyin = new Pinyin();
            $username = $pinyin->name($param['name'], PINYIN_UMLAUT_V);
            $param['username'] = implode('', $username);
            if (!empty($param['id']) && $param['id'] > 0) {
                if($param['id'] == 1){
                    return to_assign(1, '超级管理员资料不支持修改');
                }
                $count = Db::name('Admin')->where([['username','=',$param['username']],['id','<>',$param['id']],['status','>=',0]])->count();
                if ($count > 0) {
                    $count_e = Db::name('Admin')->where([['username', 'like', $param['username'].'%']])->count();
                    $param['username'] = implode('', $username) . $count_e;
                }
                try {
                    validate(AdminCheck::class)->scene('edit')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                // 启动事务
                Db::startTrans();
                try {
                    Db::name('Admin')->where(['id' => $param['id']])->strict(false)->field(true)->update($param);
                    if (!isset($param['thumb']) || $param['thumb'] == '') {
                        $char = mb_substr($param['name'], 0, 1, 'utf-8');
                        Db::name('Admin')->where('id', $param['id'])->update(['thumb' => $this->to_avatars($char)]);
                    }
                    add_log('edit', $param['id'], $param);
                    //清除菜单\权限缓存
                    clear_cache('adminMenu');
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return to_assign(1, '提交失败:' . $e->getMessage());
                }
            } else {
                $count = Db::name('Admin')->where([['username', 'like', $param['username'].'%']])->count();
                if ($count > 0) {
                    $param['username'] = implode('', $username) . $count;
                }
                try {
                    validate(AdminCheck::class)->scene('add')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $param['salt'] = set_salt(20);
                $param['pwd'] = set_password($param['reg_pwd'], $param['salt']);
                // 启动事务
                Db::startTrans();
                try {
                    $uid = Db::name('Admin')->strict(false)->field(true)->insertGetId($param);
                    if (!isset($param['thumb']) || $param['thumb'] == '') {
                        $char = mb_substr($param['name'], 0, 1, 'utf-8');
                        Db::name('Admin')->where('id', $uid)->update(['thumb' => $this->to_avatars($char)]);
                    }
                    add_log('add', $uid, $param);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return to_assign(1, '提交失败:' . $e->getMessage());
                }
            }
            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            $department = set_recursion(get_department());
            $position = Db::name('Position')->where('status', '>=', 0)->order('create_time asc')->select();
            $industry = Db::name('Industry')->select();
            View::assign('industry', $industry);
            if ($id > 0) {
                $detail = get_admin($id);
                View::assign('detail', $detail);
            } else {
                //初始化密码
                //$reg_pwd = set_salt(6);
                $reg_pwd = '123123';
                View::assign('reg_pwd', $reg_pwd);
            }
            View::assign('department', $department);
            View::assign('position', $position);
            View::assign('id', $id);
            return view();
        }
    }
    //生成头像
    public function to_avatars($char)
    {
        $defaultData = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'S', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾',
            '一', '二', '三', '四', '五', '六', '七', '八', '九', '十');
        if (isset($char)) {
            $Char = $char;
        } else {
            $Char = $defaultData[mt_rand(0, count($defaultData) - 1)];
        }
        $OutputSize = min(512, empty($_GET['size']) ? 36 : intval($_GET['size']));

        $Avatar = new MDAvatars($Char, 256, 1);
        $avatar_name = '/avatars/avatar_256_' . set_salt(10) . time() . '.png';
        $path = get_config('filesystem.disks.public.url') . $avatar_name;
        $res = $Avatar->Save('.' . $path, 256);
        $Avatar->Free();
        return $path;
    }
    //删除专家回复
    public function delete_recover()
    {
        $id = get_params("id");
        $type = get_params("type");
        //pr($type);
        if($type=='recover'){
            if (Db::name('recover')->delete($id) !== false) {
                add_log('delete', $id);
                return to_assign(0, "删除成功");
            } else {
                return to_assign(1, "删除失败");
            }
        }else{

            if (Db::name('recover_company')->delete($id) !== false) {
                add_log('delete', $id);
                return to_assign(0, "删除成功");
            } else {
                return to_assign(1, "删除失败");
            }
        }
        
    }
}
